<?php

/*
  PHP version 5
  Copyright (c) 2002-2010 ECISP.CN
  声明：这不是一个免费的软件，请在许可范围内使用

  作者：Bili E-mail:huangqyun@163.com  QQ:6326420
  http://www.ecisp.cn	http://www.easysitepm.com
 */

class functioninc {
	/**
	 * php处理csv数据
	 * @param $handle一个文件
	 * @param $length
	 * @param $d
	 * @param $e
	 */
	function fgetcsv_reg(& $handle, $length = null, $d = ',', $e = '"') {
		$d = preg_quote($d);
		$e = preg_quote($e);
		$_line = "";
		$eof = false;
		while ($eof != true) {
			$_line .= ( empty($length) ? @fgets($handle) : @fgets($handle, $length));
			$itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
			if ($itemcnt % 2 == 0) $eof = true;
		}
		$_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
		$_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
		preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
		$_csv_data = $_csv_matches[1];
		for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
			$_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1', $_csv_data[$_csv_i]);
			$_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
		}
		return empty($_line) ? false : $_csv_data;
	}
	/**
	 * 对象转换为数组
	 * @param unknown_type $object
	 */
	function objectToArray(&$object) {
		$object = (array) $object;
		foreach ($object as $key => $value) {
			if (is_object($value) || is_array($value)) {
				$this->objectToArray($value);
				$object[$key] = $value;
			}
		}
	}
	/**
	 * 写文件
	 * @param $fileName
	 * @param $content
	 * @param $type
	 */
	function filewrite($fileName, $content, $type="wb+") {
		if (empty($fileName)) {
			return false;
		}
		$fd = fopen($fileName, $type);
		if ($fd) {
			fwrite($fd, $content);
			fclose($fd);
			return true;
		} else {
			return false;
		}
	}

	function fileArrayet($path) {
		if (!file_exists($path)) {
			return false;
		}
		$arr = array();
		$str = @file_get_contents($path);
		if (!empty($str)) {
			$tmp_arr = explode("\n", $str);
			foreach ($tmp_arr as $val) {
				$val = trim($val, "\r;");
				if (!empty($val)) {
					list($table, $count) = explode(':', $val);
					$arr[$table] = $count;
				}
			}
		}
		return $arr;
	}
	//删除文件
	function delfile($file) {
		if (!is_dir($file)) {
			if (is_file($file)) {

				if (!@is_writable($file)) @chmod($file, 0777);
				return unlink($file);
			}else {
				return false;
			}
		} else {
			$this->delDir($file);
		}
	}
	
	function message($str)
	{
		$alert = $str != "" ? "alert('".$str."');" : "";
		$message =  "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /><script>".$alert."history.go(-1);</script>";
		exit($message);
	}

	function redirect($str,$url)
	{
		$alert = $str != "" ? "alert('".$str."');" : "";
		$message =  "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /><script>".$alert."location.href='".$url."';</script>";
		exit($message);
	}
	
	//删除目录
	function delDir($dirName) {
		if ($handle = opendir($dirName)) {
			while (false !== ($item = readdir($handle))) {
				if ($item != '.' && $item != '..') {
					if (is_dir("$dirName/$item")) {
						$this->delDir("$dirName/$item");
					} else {
						@unlink("$dirName/$item");
					}
				}
			}
			closedir($handle);
			if (@rmdir($dirName)) return false;
		}
	}
	//获取随机数
	function random($length, $numeric=0) {
		PHP_VERSION < '4.2.0' && mt_srand((double) microtime() * 1000000);
		if ($numeric) {
			$hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
		} else {
			$hash = '';
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
			$max = strlen($chars) - 1;
			for ($i = 0; $i < $length; $i++) {
				$hash.=$chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}
	//得到随机数
	function get_random() {
		$str = time();
		for ($i = 0; $i < 6; $i++) {
			$str .= chr(mt_rand(97, 122));
		}
		return $str;
	}

	function setcookie($key, $value, $life=0) {
		$this->time = time();

		setcookie($key, $value, ($life ? time() + $life : 0), '/', '', ($_SERVER['SERVER_PORT'] == 443 ? 1 : 0));
	}
	/**
	 * 字符串加密解密
	 * @param string $string
	 * @param string $operation
	 * @param string $key
	 */
	function eccode($string, $operation='DECODE', $key='hcfly%#%#@yinyud#^$#ing82007^#^#11out7k7k') {
		$result = '';
		if ($operation == 'ENCODE') {
			for ($i = 0; $i < strlen($string); $i++) {
				$char = substr($string, $i, 1);
				$keychar = substr($key, ($i % strlen($key)) - 1, 1);
				$char = chr(ord($char) + ord($keychar));
				$result.=$char;
			}
			$result = base64_encode($result);
			$result = str_replace(array('+', '/', '='), array('-', '_', ''), $result);
		} elseif ($operation == 'DECODE') {
			$data = str_replace(array('-', '_'), array('+', '/'), $string);
			$mod4 = strlen($data) % 4;
			if ($mod4) {
				$data .= substr('====', $mod4);
			}
			$string = base64_decode($data);
			for ($i = 0; $i < strlen($string); $i++) {
				$char = substr($string, $i, 1);
				$keychar = substr($key, ($i % strlen($key)) - 1, 1);
				$char = chr(ord($char) - ord($keychar));
				$result.=$char;
			}
		}
		return $result;
	}

	function noncefile() {
		$noncefile = $this->accept('point', 'R') . $this->accept('archive', 'R') . $this->accept('action', 'R');
		return $noncefile;
	}

	function daddslashes($string, $force=0, $strip=FALSE) {
		if (!get_magic_quotes_gpc() || $force == 1) {
			if (is_array($string)) {
				foreach ($string as $key => $val) {
					$string[$key] = addslashes($strip ? stripslashes($val) : $val);
				}
			} else {
				$string = addslashes($strip ? stripslashes($string) : $string);
			}
		}
		return $string;
	}

	function stripslashes($string) {

		if (is_array($string)) {
			foreach ($string as $key => $val) {
				$string[$key] = $this->stripslashes($val);
			}
		} else {
			$string = stripslashes($string);
		}
		return $string;
	}

	function preg_htmldecode($string) {
		if (is_array($string)) {
			foreach ($string as $key => $val) {
				$string[$key] = $this->preg_htmldecode($val);
			}
		} else {
			$string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
			$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
		}
		return $string;
	}
	/**
	 * 把一些预定义的字符转换为 HTML 实体
	 * @param unknown_type $str
	 */
	function htmldecode($str) {
		if (empty($str)) return $str;
		if (!is_array($str)) {
			$str = htmlspecialchars(trim($str));
			$str = str_ireplace("Xss", "", $str);
		} else {
			foreach ($str as $key => $val) {
				$str[$key] = htmlspecialchars($val);
				$str[$key] = $this->htmldecode($val);
			}
		}
		return $str;
	}

	function codecon($str, $ectype='ub') {
		if (empty($str)) return $str;
		if (!is_array($str)) {
			$str = (admin_LNG == 'big5') ? $this->codeing($str, $ectype) : $str;
		} else {
			foreach ($str as $key => $val) {
				$str[$key] = (admin_LNG == 'big5') ? $this->codeing($val, $ectype) : $val;
			}
		}
		return $str;
	}
	/**
	 * 表单非法内容替换
	 * @param string $str
	 */
	function inputcodetrim($str) {
		if (empty($str)) return $str;
		$str = str_replace("&amp;", "&", $str);
		$str = str_replace("&gt;", ">", $str);
		$str = str_replace("&lt;", "<", $str);
		$str = str_replace("&lt;", "<", $str);
		$str = str_ireplace("select", "", $str);
		$str = str_ireplace("join", "", $str);
		$str = str_ireplace("union", "", $str);
		$str = str_ireplace("where", "", $str);
		$str = str_ireplace("insert", "", $str);
		$str = str_ireplace("delete", "", $str);
		$str = str_ireplace("update", "", $str);
		$str = str_ireplace("like", "", $str);
		$str = str_ireplace("drop", "", $str);
		$str = str_ireplace("create", "", $str);
		$str = str_ireplace("modify", "", $str);
		$str = str_ireplace("rename", "", $str);
		$str = str_ireplace("count", "", $str);
		$str = str_ireplace("from", "", $str);
		$str = str_ireplace("group by", "", $str);
		$str = str_ireplace("concat", "", $str);
		$str = str_ireplace("alter", "", $str);
		$str = str_ireplace("ca&#115;", "cast", $str);
		$str = preg_replace("/<span[^>]+>/i", "<span>", $str);
		$str = preg_replace("/<p[^>]+>/i", "<p>", $str);
		$str = preg_replace("/<font[^>]+>/i", "<font>", $str);
		$str = preg_replace("/width=(\'|\")?[\d%]+(\'|\")?/i", "", $str);
		$str = preg_replace("/height=(\'|\")?[\d%]+(\'|\")?/i", "", $str);
		$str = preg_replace("'<style[^\f]*?(\/style>)'si", "", $str);
		return $str;
	}
	/**
	 * 换行
	 * @param string $coffee
	 */
	function br2nl($coffee) {
		$coffee = str_replace("\r\n", "\n", $coffee);
		$coffee = str_replace("<br />\n", "\n", $coffee);
		return $coffee;
	}
	/**
	 * 接收类型
	 * @param 表单名称 $k
	 * @param 接收类型 $var
	 * @param bool $htmlcode
	 * @param bool $rehtml
	 */
	function accept($k, $var='R', $htmlcode=true, $rehtml=false) {
		switch ($var) {
			case 'G':
				$var = &$_GET;
				break;
			case 'P':
				$var = &$_POST;
				break;
			case 'C':
				$var = &$_COOKIE;
				break;
			case 'R':
				$var = &$_GET;
				if ($var[$k]=='') {
					$var = &$_POST;
				}
				break;
		}
		$putvalue = isset($var[$k]) ? $this->daddslashes($var[$k], 0) : NULL;
		$putvalue = trim($putvalue);
		return $htmlcode ? ($rehtml ? $this->preg_htmldecode($putvalue) : $this->htmldecode($putvalue)) : $putvalue;
	}

	function acceptset($value) {
		return!empty($value) ? $this->daddslashes($value, 1, 1) : NULL;
	}
	/**
	 * 字符串元素验证
	 * @param string $string
	 * @param string $strcontent
	 */
	function screening_key($string, $strcontent) {
		$string = strtolower($string);
		$matched = preg_match('/' . $strcontent . '/i', $string, $result);
		if ($matched && isset($result[0]) && strlen($result[0]) > 0) {
			if (strlen($result[0]) == 2) {
				$matched = preg_match('/' . $strcontent . '/iu', $string, $result);
			}
			if ($matched && isset($result[0]) && strlen($result[0]) > 0) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	/**
	 * 树形列表
	 * @param int $int
	 * @param string $fontline
	 */
	function treelist($int, $fontline='─') {
		if (empty($int)) {
			return false;
		}
		$result = null;
		for ($i = 0; $i <= $int; $i++) {
			$result.=$fontline;
		}
		return $result;
	}
	/**
	 * 转换IP格式
	 * @param $str
	 * @param $type
	 */
	function ip($str, $type=1) {
		if (empty($str)) {
			return false;
		} else {
			if ($type) {
				$ip = ip2long($str);
			} else {
				$ip = long2ip($str);
			}
		}
		return $ip;
	}
	
	/**
	 * 根据IP得到IP所在位置
	 * return Array ( [0] => 61.164.140.51 [1] => [2] => 浙江省 [3] => 温州市 )
	 *        Array ( [0] => 59.108.158.91 [1] => [2] => 北京市 [3] => ) 
	 */
	function get_ip_place(){    
		$ip=file_get_contents("http://fw.qq.com/ipaddress");    
		$ip=str_replace('"',' ',$ip);    
		$ip2=explode("(",$ip);    
		$a=substr($ip2[1],0,-2);    
		$b=explode(",",$a);    
		return $b;    
	}
	/**
	 * curl模拟POST提交的curl函数
	 * @param $url 模拟post或者get提交的url
	 */
	function get_curl($url,$useragent='',$referer='') {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
	    curl_setopt($ch, CURLOPT_REFERER,$referer);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$res = curl_exec($ch);
		curl_close($ch);
		return $res;
	}
	/**
	 * 模拟POST或者GET提交
	 * $url 提交的地址
	 * $post 提交的内容
	 * $type 提交类型post,get,soap
	 */
	function fsock_open($url, $limit = 0, $post = '',$type = 'GET', $cookie = '', $bysocket = false, $ip = '', $timeout = 300, $block = true) {
		$return = '';
		$matches = parse_url($url);
		!isset($matches['host']) && $matches['host'] = '';
		
		$host = $matches['host'];
		$port = !empty($matches['port']) ? $matches['port'] : 80;
		if($type == "POST") {
			$path = $url;
			$out = "POST $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			//$out .= "Referer: $boardurl\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
			$out .= "User-Agent: Mozilla/4.0(compatible;MSIE 7.0;Windows NT 5.1)\r\n";
			$out .= "Host: $host\r\n";
			$out .= 'Content-Length: '.strlen($post)."\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cache-Control: no-cache\r\n";
			$out .= "Cookie: $cookie\r\n\r\n";
			$out .= $post;
		} else if($type == "SOAP") {
			$path = $url;
			$out .= "POST $path HTTP/1.1\r\n";
			$out .= "Host: $host\r\n";
			$out .= "Content-Type: application/soap+xml; charset=utf-8\r\n";
			$out .= "Content-Length: ".strlen($post)."\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cache-Control: no-cache\r\n";
			$out .= "Cookie: \r\n\r\n";
			$out .= $post;
		} else if($type == "GET") {
			$path = $url ."?". $post;
			echo $path;
			exit;
			$out = "GET $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			//$out .= "Referer: $boardurl\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
			$out .= "Host: $host\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cookie: $cookie\r\n\r\n";
		}
		$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
		if(!$fp) {
			return '';//note $errstr : $errno \r\n
		} else {
			stream_set_blocking($fp, $block);
			stream_set_timeout($fp, $timeout);
			@fwrite($fp, $out);
			$status = stream_get_meta_data($fp);
			if(!$status['timed_out']) {
				while (!feof($fp)) {
					if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
						break;
					}
				}
				$stop = false;
				while(!feof($fp) && !$stop) {
					$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
					$return .= $data;
					if($limit) {
						$limit -= strlen($data);
						$stop = $limit <= 0;
					}
				}
			}
			@fclose($fp);
			return $return;
		}
	}
	function get_remotefile($url,$useragent,$referer) {
		$optionget = array('http' => array('method' => "GET", 'header' => "User-Agent:$useragent\r\nAccept:*/*\r\nReferer:$referer\r\n"));    
	    $arr = file($url, false , stream_context_create($optionget));    
		$content=implode('',$arr);
		return $content;
	}
	//判断是否为utf-8
	function is_utf8($word)
	{ 
		$res = false;
		if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$word) == true) 
		{
			$res = true; 
		}
		return $res;
	}
	
	/**
	 * soap提交时的数据
	 * @param string $username
	 * @param string $password
	 */
	function soap_data_login($username,$password) {
		$data .= "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
		$data .= "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\r\n";
		$data .= "  <soap12:Body>\r\n";
		$data .= "    <Login xmlns=\"http://elong.com/NorthBoundAPI/\">\r\n";
		$data .= "      <loginRequest>\r\n";
		$data .= "        <UserName>$username</UserName>\r\n";
		$data .= "        <Password>$password</Password>\r\n";
		$data .= "      </loginRequest>\r\n";
		$data .= "    </Login>\r\n";
		$data .= "  </soap12:Body>\r\n";
		$data .= "</soap12:Envelope>\r\n";
		return $data;
	}

	/**
	 * 编码转换
	 * @param <type> $out		要转换的文字
	 * @param <type> $getcode	要转换的编码 ub:UTF-GIB5  bu:将GIB5转换为UTF－8 ug:  gu:将GB2312转换为UTF8
	 * @return <type>
	 */
	function codeing($out, $getcode='ub') {
		require_once admin_ROOT . 'public/class.Chinese.php';
		$codechange = new Chinese(admin_ROOT . 'public/config/');
		if ($getcode == 'ub') {
			$out = $codechange->u2g($out);
			$out = $codechange->g2b($out);
		} elseif ($getcode == 'bu') {
			$out = $codechange->b2u($out);
		} elseif ($getcode == 'ug') {
			$out = $codechange->u2b($out);
			$out = $codechange->b2g($out);
			$out = $codechange->g2u($out);
		} elseif ($getcode == 'gu') {
			$out = $codechange->g2u($out);
		} elseif ($getcode == 'gb') {
			$out = $codechange->g2b($out);
		}
		return $out;
	}
	/**
	 * 两个值相等则返回 "selected"
	 * @param unknown_type $lng1
	 * @param unknown_type $lng2
	 */
	function lngsel($lng1, $lng2) {
		if ($lng2 == $lng1) {
			$sel_str = 'selected';
		} else {
			$sel_str = '';
		}
		$lngsel = $sel_str;
		return $lngsel;
	}
	/**
	 * 返回时间格式
	 * @param int $time  时间戳
	 * @param ing $type
	 */
	function formatdate($time, $type=3) {

		$time = empty($time) ? time() : ((strstr($time, ':') || strstr($time, '-')) ? strtotime($time) : $time);
		switch ($type) {
			case 1:
				$format = date('H:i:s', $time);
				break;
			case 2:
				$format = date('Y-m-d', $time);
				break;
			case 3:
				$format = date('Y-m-d H:i:s', $time);
				break;
			case 4:
				$format = $time;
				break;
		}
		return $format;
	}
	function format_week($timestamp) {
		if (empty($timestamp)) {
			$timestamp = time();
		}
		$w = date('N',$timestamp); $s = "";
		switch($w) {
			case 1:
			{
				$s = "周一";	
				break;
			}
			case 2:
			{
				$s = "周二";	
				break;
			}
			case 3:
			{
				$s = "周三";	
				break;
			}
			case 4:
			{
				$s = "周四";	
				break;
			}
			case 5:
			{
				$s = "周五";	
				break;
			}
			case 6:
			{
				$s = "周六";	
				break;
			}
			case 7:
			{
				$s = "周日";	
				break;
			}
		}
		return $s;
	}
	/**
	 * 格式化字节大小
	 * @param int $size
	 */
	function format_size($size) {
		if ($size < 1000) {
			$size_BKM = (string) $size . ' B';
		} elseif ($size < (1000 * 1000)) {
			$size_BKM = number_format((double) ($size / 1000), 1) . ' KB';
		} else {
			$size_BKM = number_format((double) ($size / (1000 * 1000)), 1) . ' MB';
		}
		return $size_BKM;
	}
	/**
	 * 缓存的ID
	 */
	function cache_id() {

		$SELF = 'http://' . $_SERVER[HTTP_HOST] . $_SERVER[PHP_SELF] . $_SERVER['QUERY_STRING'];

		$cache_id = md5($SELF);
		return $cache_id;
	}
	/**
	 * 反序列化一个字符串对象为一个数组
	 * @param string $cfg
	 * return array
	 */
	function formatarray($cfg) {
		if (is_string($cfg) && ($arr = unserialize($cfg)) !== false) {
			$config = array();
			foreach ($arr as $key => $val) {
				$config[$val['name']] = $val['value'];
			}
			return $config;
		} else {
			return false;
		}
	}
	/**
	 * 返回目录中的文件名
	 * @param string $directory
	 */
	function readplug($directory) {
		$dir = @opendir($directory);
		$modulesid = true;
		$modules = array();
		while (false !== ($file = @readdir($dir))) {
			if (preg_match("/^.*?\.php$/", $file)) {
				require $directory . '/' . $file;
			}
		}
		@closedir($dir);

		unset($modulesid);
		foreach ($modules as $key => $value) {

			ksort($modules[$key]);
		}
		ksort($modules);
		return $modules;
	}
	/**
	 * 判断目录是否可读可写等。
	 * @param string $file 目录路径
	 * @param string $checktype
	 */
	function filemode($file, $checktype='w') {

		if (!file_exists($file)) {
			return false;
		}
		if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {

			$testfile = $file . 'writetest.txt';

			if (is_dir($file)) {

				$dir = @opendir($file);

				if ($dir === false) {
					return false;
				}

				if ($checktype == 'r') {
					$mode = (@readdir($dir) != false) ? true : false;
					@closedir($dir);
					return $mode;
				}

				if ($checktype == 'w') {
					$fp = @fopen($testfile, 'wb');
					if ($fp != false) {
						$wp = @fwrite($fp, 'demo');
						$mode = ($wp != false) ? true : false;
						@fclose($fp);
						@unlink($testfile);
						return $mode;
					} else {
						return false;
					}
				}
			} elseif (is_file($file)) {

				if ($checktype == 'r') {
					$fp = @fopen($file, 'rb');
					@fclose($fp);
					$mode = ($fp != false) ? true : false;
					return $mode;
				}

				if ($checktype == 'w') {
					$fp = @fopen($file, 'ab+');
					if ($fp != false) {
						$wp = @fwrite($fp, "");
						$mode = ($wp != false) ? true : false;
						@fclose($fp);
						return $mode;
					} else {
						return false;
					}
				}
			}
		} else {

			if ($checktype == 'r') {
				$fp = @is_readable($file);
				$mode = ($fp) ? true : false;
				return $mode;
			}

			if ($checktype == 'w') {
				$fp = @is_writable($file);
				$mode = ($fp) ? true : false;
				return $mode;
			}
		}
	}
	/**
	 * 拷贝文件
	 * @param string $srcdir  文件目录源
	 * @param string $dstdir  拷贝到目录
	 * @param bool $verbose
	 */
	function dircopy($srcdir, $dstdir, $verbose = false) {
		$num = 0;
		if (!is_dir($dstdir)) mkdir($dstdir, 0777, true);
		if ($curdir = opendir($srcdir)) {
			while ($file = readdir($curdir)) {
				if ($file != '.' && $file != '..') {
					$srcfile = $srcdir . '\\' . $file;
					$dstfile = $dstdir . '\\' . $file;
					if (is_file($srcfile)) {
						if (is_file($dstfile)) $ow = filemtime($srcfile) - filemtime($dstfile); else $ow = 1;
						if ($ow > 0) {
							if (copy($srcfile, $dstfile)) {
								touch($dstfile, filemtime($srcfile));
								$num++;
							} else {
								continue;
							}
						}
					} else if (is_dir($srcfile)) {
						$num += dircopy($srcfile, $dstfile);
					}
				}
			}
			closedir($curdir);
		}
		return $num;
	}
	/**
	 * 取得目录文件大小
	 * @param str $dir
	 */
	function dirsize($dir) {
		$handle = opendir($dir);
		$size = 0;
		while ($file = readdir($handle)) {
			if (($file == ".") || ($file == "..")) continue;
			if (is_dir("$dir/$file")) $size+=$this->dirsize("$dir/$file");
			else $size+=filesize("$dir/$file");
		}
		closedir($handle);
		return $size;
	}
	/**
	 * 把字节转换MB
	 * @param $num
	 * $num = 1353333
	 * return 1.3 MB
	 */
	function num_bitunit($num) {
		$bitunit = array(' B', ' KB', ' MB', ' GB');
		for ($key = 0, $count = count($bitunit); $key < $count; $key++) {

			if ($num >= pow(2, 10 * $key) - 1) {
				$num_bitunit_str = (ceil($num / pow(2, 10 * $key) * 100) / 100) . " $bitunit[$key]";
			}
		}
		return $num_bitunit_str;
	}
	/**
	 * 清除内 容的链接
	 * @param string $body
	 * @param string $http
	 */
	function linkclear($body, $http=null) {
		$body = $this->stripslashes($body);
		$body = html_entity_decode($body);
		$basehost = empty($http) ? $_SERVER['HTTP_HOST'] : $http;
		preg_match_all('/<a[\s\S]*?href=["|\']?([^>"\' ]+)["|\']?\s*[^>]*>(.+?)<\/a>/si', $body, $att);
		if (count($att[1]) > 0) {
			foreach ($att[1] as $key => $value) {
				$leftstr = substr($value, 0, 1);
				$leftlent = stripos('#' . $value, $basehost);
				if ($leftlent < 1 && $leftstr != '/' && $leftstr != '.') {
					$body = str_replace($att[0][$key], $att[2][$key], $body);
				}
			}
		}
		$body = $this->daddslashes($body, 1);
		$body = htmlspecialchars($body);
		return $body;
	}
	/**
	 * 字符串过滤处理
	 * @param string $body
	 * @param int $len
	 */
	function get_substr($body, $len=0) {
		if (empty($body)) return false;
		if ($len < 1) return false;
		$body = $this->stripslashes($body);//删除由 addslashes() 函数添加的反斜杠

		$body = html_entity_decode($body);  //把 HTML 实体转换为字符
		$body = trim(strip_tags($body));   //剥去 HTML、XML 以及 PHP 的标签
		$str = substr($body, 0, $len);
		return $str;
	}
	/**
	 * 字符串截取
	 * @param $str
	 * @param $slen
	 * @param $startdd
	 */
	function substr($str, $slen, $startdd=0) {
		$str = $this->substr_utf8(stripslashes($str), $slen, $startdd);
		return addslashes($str);
	}

	/**
	 * 字符串截取，返回字符串的一部分
	 * @param strging $str
	 * @param int $length
	 * @param int $start
	 */
	function substr_utf8($str, $length, $start=0) {
		if (strlen($str) < $start + 1) {
			return '';
		}
		preg_match_all("/./su", $str, $ar);
		$str = '';
		$tstr = '';
		for ($i = 0; isset($ar[0][$i]); $i++) {
			if (strlen($tstr) < $start) {
				$tstr .= $ar[0][$i];
			} else {
				if (strlen($str) < $length + strlen($ar[0][$i])) {
					$str .= $ar[0][$i];
				} else {
					break;
				}
			}
		}
		return $str;
	}
	/**
	 * 数据数组与用户数组元素合并，如果在数据里存在在加上selected
	 * @param $array1
	 * @param $array2
		array1 = array('attrname'=>'xueli','attrvalue'=>array('初中以上','高中以上','大专以上','本科以上'));
		array2 = array('xueli' => "本科以上",'xingbe' => "男性",'jingyan' => "二年以上",'zhizhe' => "",'renshu' => 2)
	 */
	function array_merge($array1=array(), $array2=array()) {
		if (empty($array1) || count($array1) < 1) return array();


		foreach ($array1 as $key => $value) {

			if (!is_array($value['attrvalue'])) {
				$array1[$key]['attrvalue'] = stripslashes($array2[$value['attrname']]);
			} else {
				$valuename = $array2[$value['attrname']];
				if (!is_array($valuename)) {

					foreach ($value['attrvalue'] as $var => $gvalue) {
						if (trim($gvalue['name']) == trim($valuename)) {
							$array1[$key]['attrvalue'][$var]['selected'] = 'selected';
						}
					}
				} else {

					foreach ($valuename as $vk => $attvalue) {
						foreach ($value['attrvalue'] as $var => $gvalue) {
							if (trim($attvalue) == trim($gvalue['name'])) {
								$array1[$key]['attrvalue'][$var]['selected'] = 'selected';
							}
						}
					}
				}
			}
		}
		return $array1;
	}
	/**
	 * 给定值是否在数组里面，如果在在选定他。
	 * @param 原有数组 $array
	 * @param 给定值 $nowarray
	 * @param 键值 $compare
	 */
	function reset_array($array, $nowarray=null, $compare=null) {
		if (!is_array($array)) return $array;
		if (count($array) <= 0) return $array;
		if ($nowarray == null) return $array;
		if ($compare == null) return $array;
		foreach ($array as $key => $value) {
			if ($nowarray == $value[$compare]) {
				$array[$key]['selected'] = 'selected';
			} else {
				$array[$key]['selected'] = '';
			}
		}
		return $array;
	}
	/**
	 * 根据时间和随机字符得到一个字符串
	 * @param string $str
	 */
	function get_tsn($str='SN') {
		$str_t = date("YmdHis");
		$rand = rand(100, 999);
		$str_t = "$str$str_t$rand";
		return $str_t;
	}
	/**
	 * 得到一个字符串
	 * @param 长度 $len
	 */
	function getStr($len=6) {
		$str = 'ACBDEFGHIJKLMNOPQRSTUVWXYZacbdefghijklmnopqrstuvwxyZ0123456789';
		$str = str_shuffle($str);  //顺序打乱
		$str = str_repeat($str, 5);
		return substr(str_shuffle($str), 0, $len);
	}
	/**
	 * 把数组格式化为字符串
	 * @param array $array 数组
	 * @param string $str 分隔符
	 */
	function format_array_text($array=array(), $str=',') {
		$out_str = null;
		if (is_array($array)) {
			$str_newarray = implode($str, $array);
		} else {
			$str_array = explode($str, $array);
			$str_newarray = array();
			if (is_array($str_array)) {
				foreach ($str_array as $key => $value) {
					if (!empty($value)) {
						$str_newarray[] = $value;
					}
				}
			}
		}
		return $str_newarray;
	}
	/**
	 * 把数组的下标做成数组，***_config 表用到 
	 * @param array $array
	 * @param 数组键值 $key
	 * @param 数组值 $name
	 * array(
	 * 		array('valname'=>'icpbeian','content'=>'ICP备案'),
	 * 		array('valname'=>'is_close','content'=>'网站状态')
	 * )
	 * return array(
	 * 		'icpbeian' => 'ICP备案',
	 * 		'is_close' => '网站状态'
	 * )
	 */
	function key_array_name($array=array(), $key=null, $name=null) {
		if (!is_array($array) || count($array) < 1) return false;
		$str_array = array();
		foreach ($array as $i => $value) {
			$newkey = $value[$key];
			$newname = $value[$name];
			$str_array[$newkey] = $newname;
		}
		return $str_array;
	}

	function get_timemessage($timenow) {
		$morentime1 = strtotime('1:00');
		$morentime2 = strtotime('6:00');
		$morentime3 = strtotime('12:00');
		$morentime4 = strtotime('19:00');
		$morentime5 = strtotime('19:00');
		if ($timenow < $morentime1) {
			$str = "深夜了，请注意休息！";
		} elseif ($timenow < $morentime2) {
			$str = "早上好！";
		} elseif ($timenow < $morentime3) {
			$str = "中午好！";
		} elseif ($timenow < $morentime4) {
			$str = "下午好！";
		} elseif ($timenow < $morentime5) {
			$str = "晚上好！";
		}
		return $str;
	}

}
?>
